package cn.sun.order.service.impl;

import cn.sun.basic.service.impl.BaseServiceImpl;
import cn.sun.basic.util.AjaxResult;
import cn.sun.basic.util.CodeGenerateUtils;
import cn.sun.basic.util.PageBean;
import cn.sun.basic.util.StrUtils;
import cn.sun.order.domain.AdoptOrder;
import cn.sun.order.domain.OrderAddress;
import cn.sun.order.mapper.AdoptOrderMapper;
import cn.sun.order.mapper.OrderAddressMapper;
import cn.sun.order.query.AdoptOrderQuery;
import cn.sun.order.service.IAdoptOrderService;
import cn.sun.org.domain.Employee;
import cn.sun.org.mapper.EmployeeMapper;
import cn.sun.pay.constants.PayConstants;
import cn.sun.pay.domain.PayBill;
import cn.sun.pay.mapper.PayBillMapper;
import cn.sun.pay.service.IPayBillService;
import cn.sun.pet.domain.Pet;
import cn.sun.pet.mapper.PetMapper;
import cn.sun.user.domain.LoginInfo;
import cn.sun.user.domain.User;
import cn.sun.user.domain.UserAddress;
import cn.sun.user.mapper.UserAddressMapper;
import cn.sun.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder,AdoptOrderQuery> implements IAdoptOrderService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;
    @Override
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        Long petId = Long.valueOf(params.get("pet_id").toString()); //宠物id
        Long addressId = Long.valueOf(params.get("address_id").toString());//用户地址id
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString()); //配送方式
        Integer payMethod = Integer.valueOf(params.get("pay_method").toString()); //支付方式

        Pet pet = petMapper.findById(petId);
        //1 修改宠物状态-下架
        pet.setState(0);
        pet.setOffsaletime(new Date());
        pet.setShop_id(pet.getShop_id());
        //2 绑定用户
        User user = userMapper.findByLoginInfoId(loginInfo.getId());
        pet.setUser_id(user.getId());
        pet.setUser(user);
        petMapper.update(pet);
        //3 创建领养订单
        //3.1 创建订单本身
        String unionPaySn = CodeGenerateUtils.generateUnionPaySn(); //先设置支付单号，后面直接获取
        AdoptOrder adoptOrder = initAdoptOrder(user, pet);
        adoptOrder.setPaySn(unionPaySn);
        adoptOrderMapper.save(adoptOrder);
        //@TODO 配送方式添加
        //3.2 创建订单地址
        UserAddress userAddress = userAddressMapper
                .findById(addressId);
        OrderAddress orderAddress = userAddress2OrderAddress(userAddress, adoptOrder);
        orderAddressMapper.save(orderAddress);
        //4创建支付单并发起支付请求
        //4.1 创建支付单
        PayBill payBill = buildPayBill(payMethod, pet, user, adoptOrder);
        payBillMapper.save(payBill);
        System.out.println(payBill);
        //4.2 对支付单发起支付请求-就是支付模块给我提供一个支付接口service方法
        String payData = payBillService.payRequest(payBill);
        //5 @TODO 订单倒计时取消处理
        return payData;
    }

    /**
     * 构建支付单
     * @param payMethod
     * @param pet
     * @param user
     * @param adoptOrder
     * @return
     */
    private PayBill buildPayBill(Integer payMethod, Pet pet, User user, AdoptOrder adoptOrder) {
        PayBill payBill = new PayBill();
        payBill.setDigest(adoptOrder.getDigest());
        payBill.setMoney(adoptOrder.getPrice());
        payBill.setUnionPaySn(adoptOrder.getPaySn());
        payBill.setState(0);
        payBill.setLastPayTime(new Date(System.currentTimeMillis()+PayConstants.ORDER_TIMEOUT));
        payBill.setPayChannel(Long.valueOf(payMethod));//0 余额 1 支付宝 2 微信 3 银联
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);
        payBill.setBusinessKey(adoptOrder.getId());
        payBill.setUser_id(user.getId());
        payBill.setShop_id(pet.getShop_id());
        payBill.setNickName(user.getUsername());
        return payBill;
    }


    public OrderAddress userAddress2OrderAddress(UserAddress userAddress,AdoptOrder adoptOrder){
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setId(null);
        orderAddress.setOrder_id(adoptOrder.getId());
        orderAddress.setOrderSn(adoptOrder.getOrderSn());
        return orderAddress;
    }

    public AdoptOrder initAdoptOrder(User user,Pet pet){
        AdoptOrder adoptOrder = new AdoptOrder();
        adoptOrder.setDigest("[摘要]领养"+pet.getName()+"的订单！");
        adoptOrder.setState(0); //待支付
        adoptOrder.setPrice(pet.getSaleprice()); //待支付
        adoptOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        //lastPayTime最后支付时间  当前时间+15分钟
        Date lastPayTime = new Date(System.currentTimeMillis()+PayConstants.ORDER_TIMEOUT);
        adoptOrder.setLastPayTime(lastPayTime);
        adoptOrder.setPet_id(pet.getId());
        adoptOrder.setUser_id(user.getId());
        adoptOrder.setShop_id(pet.getShop_id());
        return adoptOrder;
    }


    //用户查询是通过userId区分
    @Override
    public PageBean<AdoptOrder> queryUserOrder(AdoptOrderQuery query, LoginInfo loginInfo) {
        User user = userMapper.findByLoginInfoId(loginInfo.getId());
        query.setUserId(user.getId());
        return super.findPage(query);
    }


    //如果我们不传入shopId就是平台管理员，否则就是店铺管理员或员工
    @Override
    public PageBean<AdoptOrder> queryAdminOrder(AdoptOrderQuery query, LoginInfo loginInfo) {
        Employee employee = employeeMapper.findByLoginInfoId(loginInfo.getId());
        query.setShopId(employee.getShopId());
        return super.findPage(query);
    }

    @Override
    public void cancelByQuartz(Long orderId) {
        //查询订单信息
        AdoptOrder adoptOrder = adoptOrderMapper.findById(orderId);
        //修改订单状态
        adoptOrder.setState(-1);
        adoptOrderMapper.update(adoptOrder);

        //支付单也要修改
        String paySn = adoptOrder.getPaySn();
        PayBill payBill = payBillMapper.loadByUnionPaySn(paySn);
        payBill.setState(-1);
        payBillMapper.update(payBill);

        System.out.println(adoptOrder.getDigest()+"被quartz自动取消了！");
    }
}
